<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="formIs"
      class="bg-bg_color w-[99/100] pl-8 pt-4"
    >
      <!-- <el-form-item label="角色名称：" prop="name">
        <el-input
          v-model="formIs.admin_name"
          placeholder="请输入角色名称"
          clearable
          class="!w-[200px]"
        />
      </el-form-item> -->
      <!-- <el-form-item label="角色ID：" prop="code">
        <el-input
          v-model="formIs.role_id"
          placeholder="请输入角色ID"
          clearable
          class="!w-[180px]"
        />
      </el-form-item> -->
      <el-form-item label="角色：" prop="status">
        <el-select
          v-model="formIs.role_id"
          placeholder="请选择角色"
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in optionsRef"
            :key="item.role_id"
            :label="item.role_name"
            :value="item.role_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="loading"
          @click="onSearch(formIs.role_id)"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar title="管理员列表" @refresh="onSearch">
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="addUserAdmin()"
          v-auth="'admin_add'"
        >
          新增管理员
        </el-button>
      </template>
      <template v-slot="{ size, checkList }">
        <pure-table
          border
          ref="waterRef"
          :row-key="formIs.admin_id"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :size="size"
          :data="
            dataList.slice(
              (pagination.currentPage - 1) * pagination.pageSize,
              pagination.currentPage * pagination.pageSize
            )
          "
          :columns="columns"
          :checkList="checkList"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @selection-change="handleSelectionChange"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="handleUpdateUser(row)"
              v-auth="'admin_modify'"
            >
              修改
            </el-button>
            <el-popconfirm title="是否确认删除?" @confirm="handleDelete(row)">
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                  v-auth="'admin_delete'"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="handleRoles(row)"
              v-auth="'admin_allocation'"
            >
              分配角色
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <el-dialog
      v-model="dialogFormVisible"
      :title="titleInfo"
      :rules="rules"
      ref="formRef"
    >
      <el-form :model="formIs">
        <el-form-item
          label="头像"
          :label-width="formLabelWidth"
          prop="imageUrl"
        >
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :action="actionUrl"
            accept=".png,.jpg,.jpeg "
            :headers="headers"
            :data="additionalData"
            :before-upload="handleBeforeUpload"
          >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
              prop="imageUrl"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="账号"
          :label-width="formLabelWidth"
          prop="admin_name"
        >
          <el-input
            onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"
            @change="handleChange"
            v-model="formIs.admin_name"
            autocomplete="off"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="手机号"
          onkeyup="value=value.replace(/\D/g,'')"
          maxlength="11"
          :label-width="formLabelWidth"
          prop="admin_phone"
          clearable
        >
          <el-input v-model="formIs.admin_phone" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="密码"
          clearable
          :label-width="formLabelWidth"
          prop="admin_pass"
        >
          <el-input
            v-model="formIs.admin_pass"
            autocomplete="off"
            type="password"
          />
        </el-form-item>
        <el-form-item
          label="昵称"
          clearable
          :label-width="formLabelWidth"
          onkeyup="value=value.replace(/^[^!@#$%^&*()-=+]/g,'')"
          prop="admin_nick"
        >
          <el-input v-model="formIs.admin_nick" autocomplete="off" />
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch
            v-model="formIs.admin_status"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
        <el-form-item
          clearable
          label="角色"
          :label-width="formLabelWidth"
          prop="role_id"
        >
          <el-select v-model="formIs.role_id" class="m-2" placeholder="请选择">
            <el-option
              v-for="item in optionsRef"
              :key="item.role_id"
              :label="item.role_name"
              :value="item.role_id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="quxiao" type="danger">取消</el-button>
          <el-button type="primary" @click="handleSubmit(1)"> 提交 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogRoles" title="分配角色" width="50%">
      <el-radio-group
        v-model="checkList"
        class="ml-4"
        @change="changeCheckList"
      >
        <el-radio
          v-for="(item, index) in roleList"
          :key="index"
          :label="item.role_name"
          :value="item.role_id"
        />
      </el-radio-group>
      <template #footer>
        <span class="dialog-footer">
          <!-- <el-button @click="dialogFormVisible = false" type="danger"
            >取消</el-button
          > -->
          <el-button type="primary" @click="handleSubmit(2)"> 提交 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, inject, onMounted, toRefs } from "vue";
import { useRole } from "./hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getUpdate } from "@/api/user";
import * as CryptoJS from "crypto-js";
import { message } from "@/utils/message";
import { getSessionKey } from "@/utils/auth";
import { storageSession } from "@pureadmin/utils";
import { useUserStoreHook } from "@/store/modules/user";
// import Database from "@iconify-icons/ri/database-2-line";
// import More from "@iconify-icons/ep/more-filled";
import Refresh from "@iconify-icons/ep/refresh";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Search from "@iconify-icons/ep/search";
// import Menu from "@iconify-icons/ep/menu";
import AddFill from "@iconify-icons/ri/add-circle-line";
import {
  getUserList,
  getRoleList,
  addInsert,
  getuFile,
  getInfoAdmin
} from "@/api/user";
import { ElMessage } from "element-plus";
const headers = ref({
  //携带token传递到后端
  Authorization: "Bearer " + sessionStorage.getItem("token")
});
const imageUrl = ref(
  "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
);
const rules = {
  imageUrl: [{ required: true, message: "请先上传头像", trigger: "blur" }],
  admin_name: [{ required: true, message: "请输入用户名", trigger: "blur" }]
};
const titleInfo = ref("");
const quxiao = () => {
  dialogFormVisible.value = false;
  formIs = {};
};
const changeCheckLis = val => {
  console.log(val, "==----");
};
const additionalData = reactive({
  // 这里添加你需要传递的额外参数
  type: "admin",
  action: "loan"
});
defineOptions({
  name: "AddManageList"
});
const handleChange = value => {
  formIs.admin_name = value.replace(/[^a-zA-Z0-9]/g, "");
  formIs.admin_name = value.replace(/[@.]/g, "");
};
// 上传图片
const handleBeforeUpload = file => {
  const filesInfo = file.size / 1024 / 1024 < 2;
  if (!filesInfo) {
    ElMessageBox.alert("上传头像图片大小不能超过 2MB!");
  }
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => {
      // 转换成功，得到Base64字符串
      const base64 = e.target.result;
      // 处理Base64字符串，例如可以在这里发起接口请求
      const params = {
        ...additionalData,
        file: base64
      };
      getuFile(params).then(res => {
        if (res.code == 200) {
          imageUrl.value = base64;
          formIs.admin_image = res.data;
        }
      });
    };
    reader.onerror = reject;
    reader.readAsDataURL(file); // 转换文件为Base64
  });
};
interface FormType {
  admin_image: string;
  admin_id: string;
  admin_name: string;
  admin_pass: string;
  role_id: string;
  admin_nick: string;
  admin_status: number;
}
// interface RoleType {
//   role_id: string;
//   role_name: string;
// }
const refresh: any = inject("reload");
const dialogFormVisible = ref(false);
const formRef = ref();
const adminId = ref(false);
const waterRef = ref();
const optionsRef = ref([]);
const checkList = ref();
const roleInfo = ref({});
const dialogRoles = ref(false);
const roleList = ref([]);
const adminNick = ref("");
const adminidJiaose = ref("");
import { ElNotification } from "element-plus";
const formLabelWidth = "100px";
const imgurl = ref("");
const formIs = reactive<FormType>({
  admin_image:
    "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
  admin_id: "",
  admin_name: "",
  admin_pass: "",
  role_id: "",
  admin_nick: "",
  admin_status: 1
});

const formIsRef = ref({});
const {
  loading,
  columns,
  dataList,
  pagination,
  // buttonClass,
  onSearch,
  resetForm,
  // handleUpdate,
  handleDelete,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange
} = useRole(waterRef);
function handleUpdateUser(row) {
  const { admin_id } = row;
  const obj = {
    admin_id
  };
  getInfoAdmin(obj).then(res => {
    console.log(res);
    if (res.code == 200) {
      const resinFo = res.data;
      formIs.admin_id = resinFo.admin_id;
      formIs.admin_name = resinFo.admin_name;
      formIs.admin_pass = resinFo.admin_pass;
      formIs.admin_phone = resinFo.admin_phone;
      formIs.admin_status = resinFo.admin_status;
      formIs.admin_image = resinFo.admin_image;
      formIs.admin_pass = resinFo.admin_pass;
      formIs.role_id = resinFo.role_id;
      formIs.admin_nick = resinFo.admin_nick;
    }
  });
  adminId.value = true;
  dialogFormVisible.value = true;
}
const roleIdInFo = ref("");
//新增按钮
function addUserAdmin() {
  adminId.value = false;
  formIs.admin_id = "";
  formIs.admin_name = "";
  formIs.admin_pass = "";
  formIs.role_id = "";
  formIs.admin_nick = "";
  formIs.admin_phone = "";
  formIs.admin_image = "";
  titleInfo.value = "新增管理员";
  dialogFormVisible.value = true;
}
//获取角色列表
async function handleUserList() {
  const res = await getRoleList();
  if (res.code === 200) {
    optionsRef.value = res.data.data;
  } else {
    message(res.msg, { type: "error" });
  }
}

//新增/修改角色
async function handleSubmit(num) {
  if (num == 1) {
    // if (!formIs.admin_image) {
    //   message("请先上传头像", { type: "error" });
    //   return;
    // }

    if (!formIs.admin_name) {
      message("请先输入账号", { type: "error" });
      return;
    }
    const reg = /^1[3456789]\d{9}$/;
    if (!formIs.admin_phone) {
      message("请先输入手机号", { type: "error" });
      return;
    } else if (!reg.test(formIs.admin_phone)) {
      message("请输入正确的手机号", { type: "error" });
      return;
    }
    const regPass =/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,10}$/
    if (!formIs.admin_pass) {
      message("请先输入密码", { type: "error" });
      return;
    } else if (!regPass.test(formIs.admin_pass)) {
      message("密码格式不对", {
        type: "error"
      });
      return;
    }
    if (!formIs.admin_status) {
      message("请先选择状态", { type: "error" });
      return;
    }
    if (!formIs.admin_nick) {
      message("请先输入昵称", { type: "error" });
      return;
    }
    if (!formIs.role_id) {
      message("请先选择角色", { type: "error" });
      return;
    }
    if (checkList.value?.length) {
      console.log(roleInfo.value, checkList.value);
      formIs.admin_id = roleInfo.value.admin_id;
      formIs.admin_name = roleInfo.value.admin_name;
      formIs.admin_pass = roleInfo.value.admin_pass;
      formIs.admin_nick = roleInfo.value.admin_nick;
      formIs.role_id = optionsRef.value.filter(
        item => item.role_name == checkList.value
      )[0].role_id;
    }
    formIsRef.value = formIs;
    const encryptedFormIsRefValue = {
      ...formIs
    };
    delete encryptedFormIsRefValue.admin_id;
    const res = await addInsert(encryptedFormIsRefValue);
    if (res.code === 200) {
      if (num == 2) {
        const asyncRouteList = storageSession().getItem("user-info") as any;
        if (adminNick.value == asyncRouteList.admin_nick) {
          useUserStoreHook().logOut();
        }
      }
      message("成功", { type: "success" });
      console.log(optionsRef.value, res.data.roles);
      dialogFormVisible.value = false;
      refresh();
    } else {
      message(res.msg, { type: "error" });
    }
  } else {
    const listInfo = JSON.parse(JSON.stringify(optionsRef.value));
    listInfo.map((el, i) => {
      if (el.role_name == checkList.value) {
        roleIdInFo.value = el.role_id;
      }
    });
    const parmas = {
      role_id: roleIdInFo.value,
      admin_id: adminidJiaose.value
    };
    getUpdate(parmas).then(res => {
      if (res.code == 200) {
        message("成功", { type: "success" });
        dialogRoles.value = false;
      } else {
        message(res.msg, { type: "error" });
        dialogRoles.value = false;
      }
    });
  }
}

//分配角色
function handleRoles(row) {
  const rowData = JSON.parse(JSON.stringify(row));
  const { admin_id } = rowData;
  adminidJiaose.value = admin_id;
  roleInfo.value = row;
  adminNick.value = row.admin_nick;
  roleList.value = optionsRef.value;
  dialogRoles.value = true;
}
// 搜索
const onSearchInfo = () => {
  if (!formIs.role_id) {
    ElNotification({
      title: "温馨提示",
      message: "请先选择角色"
    });
  }
};
const getUserListData = () => {};
onMounted(() => {
  handleUserList();
  onSearch(""); //获取列表
});
</script>
<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
